<template>
  <div class="expression-editor-container">
    <n-card class="expression-editor-card">
      <template #header>
        <div class="card-header">
          <h1>{{ isNewExpression ? '创建表情' : '编辑表情' }}</h1>
          <div class="header-actions">
            <n-button @click="goBack">
              <template #icon><n-icon><ArrowBackOutline /></n-icon></template>
              返回
            </n-button>
            <n-button type="primary" @click="saveExpression">
              <template #icon><n-icon><SaveOutline /></n-icon></template>
              保存
            </n-button>
          </div>
        </div>
      </template>
      
      <div class="content-layout">
        <div class="form-section">
          <n-form
            ref="formRef"
            :model="expressionForm"
            :rules="formRules"
            label-placement="left"
            label-width="100"
            require-mark-placement="right-hanging"
          >
            <n-form-item label="表情名称" path="name">
              <n-input v-model:value="expressionForm.name" placeholder="请输入表情名称" />
            </n-form-item>
            
            <n-form-item label="分类" path="category">
              <n-select
                v-model:value="expressionForm.category"
                :options="categoryOptions"
                placeholder="请选择分类"
                tag
                clearable
              />
            </n-form-item>
            
            <n-form-item label="缩略图" path="thumbnail">
              <n-upload
                action="#"
                :default-upload="false"
                :on-before-upload="beforeUploadThumbnail"
                accept="image/*"
                list-type="image-card"
                :max="1"
              >
                <div v-if="!expressionForm.thumbnail">
                  <n-icon size="20">
                    <ImageOutline />
                  </n-icon>
                  <div>点击上传</div>
                </div>
                <img
                  v-else
                  :src="expressionForm.thumbnail"
                  alt="缩略图"
                  style="max-width: 100%; max-height: 100%"
                />
              </n-upload>
            </n-form-item>
          </n-form>
        </div>
        
        <div class="preview-section">
          <div class="preview-header">
            <h3>表情预览</h3>
            <n-button size="small" type="primary" @click="previewExpression">
              <template #icon><n-icon><PlayOutline /></n-icon></template>
              预览
            </n-button>
          </div>
          
          <div class="preview-container">
            <n-empty v-if="!character" description="请先选择角色" />
            <div v-else-if="!expressionForm.partOverrides || expressionForm.partOverrides.length === 0" class="preview-placeholder">
              <n-empty description="暂无表情数据，请添加部件覆盖" />
            </div>
            <div v-else class="character-preview">
              <!-- 这里将来会显示角色表情预览 -->
              <div class="preview-canvas">
                <img
                  v-if="expressionForm.thumbnail"
                  :src="expressionForm.thumbnail"
                  alt="表情预览"
                  class="preview-image"
                />
                <n-empty v-else description="预览图像将在这里显示" />
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <n-divider />
      
      <div class="part-overrides-section">
        <div class="section-header">
          <h3>部件覆盖</h3>
          <n-button size="small" @click="addPartOverride">
            <template #icon><n-icon><AddOutline /></n-icon></template>
            添加覆盖
          </n-button>
        </div>
        
        <div class="part-overrides-list" v-if="expressionForm.partOverrides && expressionForm.partOverrides.length > 0">
          <n-collapse>
            <n-collapse-item
              v-for="(override, index) in expressionForm.partOverrides"
              :key="index"
              :title="getPartName(override.partId)"
            >
              <template #header-extra>
                <n-button
                  quaternary
                  circle
                  size="small"
                  @click.stop="removePartOverride(index)"
                >
                  <template #icon><n-icon><TrashOutline /></n-icon></template>
                </n-button>
              </template>
              
              <n-form label-placement="left" label-width="80">
                <n-form-item label="部件">
                  <n-select
                    v-model:value="override.partId"
                    :options="characterPartsOptions"
                    placeholder="选择要覆盖的部件"
                  />
                </n-form-item>
                
                <n-form-item label="图片">
                  <n-upload
                    action="#"
                    :default-upload="false"
                    :on-before-upload="(data) => beforeUploadOverrideImage(data, override)"
                    accept="image/*"
                    list-type="image-card"
                    :max="1"
                  >
                    <div v-if="!override.imageUrl">
                      <n-icon size="20">
                        <ImageOutline />
                      </n-icon>
                      <div>点击上传</div>
                    </div>
                    <img
                      v-else
                      :src="override.imageUrl"
                      alt="覆盖图片"
                      style="max-width: 100%; max-height: 100%"
                    />
                  </n-upload>
                </n-form-item>
                
                <n-form-item label="位置" v-if="override.position">
                  <n-input-group>
                    <n-input-number
                      v-model:value="override.position.x"
                      placeholder="X"
                      :step="1"
                    />
                    <n-input-number
                      v-model:value="override.position.y"
                      placeholder="Y"
                      :step="1"
                    />
                  </n-input-group>
                </n-form-item>
                
                <n-form-item label="旋转" v-if="override.rotation !== undefined">
                  <n-input-number
                    v-model:value="override.rotation"
                    placeholder="度数"
                    :step="1"
                  />
                </n-form-item>
                
                <n-form-item label="缩放" v-if="override.scale">
                  <n-input-group>
                    <n-input-number
                      v-model:value="override.scale.x"
                      placeholder="X"
                      :step="0.1"
                    />
                    <n-input-number
                      v-model:value="override.scale.y"
                      placeholder="Y"
                      :step="0.1"
                    />
                  </n-input-group>
                </n-form-item>
              </n-form>
            </n-collapse-item>
          </n-collapse>
        </div>
        
        <n-empty
          v-else
          description="暂无部件覆盖"
        >
          <template #extra>
            <n-button @click="addPartOverride">添加部件覆盖</n-button>
          </template>
        </n-empty>
      </div>
      
      <!-- 选择部件对话框 -->
      <n-modal
        v-model:show="showPartSelectModal"
        title="选择要覆盖的部件"
        preset="dialog"
        positive-text="确认"
        negative-text="取消"
        @positive-click="confirmPartSelect"
        @negative-click="cancelPartSelect"
      >
        <n-select
          v-model:value="selectedPartId"
          :options="availablePartsOptions"
          placeholder="请选择部件"
          filterable
        />
      </n-modal>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { v4 as uuidv4 } from 'uuid'
import {
  NCard,
  NButton,
  NIcon,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NInputGroup,
  NSelect,
  NUpload,
  NEmpty,
  NDivider,
  NCollapse,
  NCollapseItem,
  NSpace,
  NModal,
  FormInst
} from 'naive-ui'
import {
  ArrowBackOutline,
  SaveOutline,
  ImageOutline,
  AddOutline,
  TrashOutline,
  PlayOutline
} from '@vicons/ionicons5'
import { useProjectStore } from '../../stores/projectStore'
import type { Expression, PartOverride, Character, CharacterPart, Vector2 } from '../../types/project'

const route = useRoute()
const router = useRouter()
const message = useMessage()
const projectStore = useProjectStore()

// 表单引用
const formRef = ref<FormInst | null>(null)

// 获取表情ID和角色ID
const expressionId = computed(() => route.params.id as string | undefined)
const characterId = computed(() => route.query.characterId as string)
const projectId = computed(() => route.query.projectId as string)
const isNewExpression = computed(() => !expressionId.value)

// 角色数据
const character = ref<Character | null>(null)

// 表情表单数据
const expressionForm = reactive<Partial<Expression>>({
  id: '',
  name: '',
  characterId: '',
  partOverrides: [],
  thumbnail: '',
  category: ''
})

// 分类选项
const categoryOptions = [
  { label: '开心', value: '开心' },
  { label: '悲伤', value: '悲伤' },
  { label: '愤怒', value: '愤怒' },
  { label: '惊讶', value: '惊讶' },
  { label: '恐惧', value: '恐惧' },
  { label: '厌恶', value: '厌恶' },
  { label: '其他', value: '其他' }
]

// 表单验证规则
const formRules = {
  name: {
    required: true,
    message: '请输入表情名称',
    trigger: 'blur'
  }
}

// 部件选择对话框
const showPartSelectModal = ref(false)
const selectedPartId = ref('')

// 角色部件选项
const characterPartsOptions = computed(() => {
  if (!character.value || !character.value.parts) return []
  
  return character.value.parts.map(part => ({
    label: part.name,
    value: part.id
  }))
})

// 可用部件选项（排除已经覆盖的部件）
const availablePartsOptions = computed(() => {
  if (!character.value || !character.value.parts) return []
  
  const usedPartIds = new Set(expressionForm.partOverrides?.map(o => o.partId) || [])
  
  return character.value.parts
    .filter(part => !usedPartIds.has(part.id))
    .map(part => ({
      label: part.name,
      value: part.id
    }))
})

// 获取部件名称
const getPartName = (partId: string) => {
  if (!character.value) return '未知部件'
  
  const part = character.value.parts.find(p => p.id === partId)
  return part ? part.name : '未知部件'
}

// 加载角色数据
const loadCharacter = async () => {
  if (!characterId.value) {
    message.error('缺少角色ID')
    return
  }
  
  try {
    const result = await projectStore.fetchCharacter(characterId.value)
    if (result) {
      character.value = result
    } else {
      message.error('加载角色数据失败')
    }
  } catch (error) {
    console.error('加载角色数据错误:', error)
    message.error('加载角色数据时发生错误')
  }
}

// 加载表情数据
const loadExpression = async () => {
  if (!expressionId.value || !characterId.value) return
  
  try {
    // 这里假设 projectStore 有 fetchExpression 方法
    // 实际项目中需要实现此方法或通过其他方式获取表情数据
    const result = await projectStore.fetchExpression(expressionId.value)
    if (result) {
      Object.assign(expressionForm, result)
    } else {
      message.error('加载表情数据失败')
    }
  } catch (error) {
    console.error('加载表情数据错误:', error)
    message.error('加载表情数据时发生错误')
  }
}

// 初始化表情数据
const initExpression = () => {
  expressionForm.id = uuidv4()
  expressionForm.characterId = characterId.value
  expressionForm.name = '新建表情'
  expressionForm.partOverrides = []
}

// 保存表情
const saveExpression = async () => {
  try {
    await formRef.value?.validate()
    
    // 这里假设 projectStore 有 saveExpression 方法
    // 实际项目中需要实现此方法或通过其他方式保存表情数据
    const result = await projectStore.saveExpression(expressionForm as Expression)
    if (result) {
      message.success('保存成功')
      if (isNewExpression.value) {
        // 如果是新建，保存后跳转到编辑页面
        router.replace(`/character/expression/${result.id}?characterId=${characterId.value}&projectId=${projectId.value}`)
      }
    } else {
      message.error('保存失败')
    }
  } catch (error) {
    console.error('保存表情错误:', error)
    message.error('表单验证失败或保存时发生错误')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 上传缩略图前处理
const beforeUploadThumbnail = (data: { file: File }) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    expressionForm.thumbnail = e.target?.result as string
  }
  reader.readAsDataURL(data.file)
  return false // 阻止默认上传行为
}

// 上传覆盖图片前处理
const beforeUploadOverrideImage = (data: { file: File }, override: PartOverride) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    override.imageUrl = e.target?.result as string
  }
  reader.readAsDataURL(data.file)
  return false // 阻止默认上传行为
}

// 添加部件覆盖
const addPartOverride = () => {
  if (!availablePartsOptions.value.length) {
    message.warning('所有部件都已添加覆盖')
    return
  }
  
  showPartSelectModal.value = true
}

// 确认选择部件
const confirmPartSelect = () => {
  if (!selectedPartId.value) {
    message.warning('请选择部件')
    return
  }
  
  // 获取选中的部件
  const part = character.value?.parts.find(p => p.id === selectedPartId.value)
  if (!part) return
  
  // 创建新的部件覆盖
  const newOverride: PartOverride = {
    partId: part.id,
    imageUrl: undefined,
    position: { x: part.position.x, y: part.position.y },
    rotation: part.rotation,
    scale: { x: part.scale.x, y: part.scale.y }
  }
  
  expressionForm.partOverrides = expressionForm.partOverrides || []
  expressionForm.partOverrides.push(newOverride)
  
  // 重置选择
  selectedPartId.value = ''
  showPartSelectModal.value = false
}

// 取消选择部件
const cancelPartSelect = () => {
  selectedPartId.value = ''
  showPartSelectModal.value = false
}

// 移除部件覆盖
const removePartOverride = (index: number) => {
  if (!expressionForm.partOverrides) return
  expressionForm.partOverrides.splice(index, 1)
}

// 预览表情
const previewExpression = () => {
  message.info('表情预览功能正在开发中')
  // 实际项目中，这里会实现表情预览功能
}

// 初始化
onMounted(async () => {
  await loadCharacter()
  
  if (expressionId.value) {
    await loadExpression()
  } else {
    initExpression()
  }
})
</script>

<style lang="scss" scoped>
.expression-editor-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .expression-editor-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .content-layout {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-bottom: 20px;
    
    .form-section {
      padding-right: 12px;
    }
    
    .preview-section {
      .preview-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        
        h3 {
          margin: 0;
        }
      }
      
      .preview-container {
        border: 1px dashed var(--border-color);
        border-radius: 4px;
        height: 300px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .character-preview {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .preview-canvas {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .preview-image {
              max-width: 100%;
              max-height: 100%;
              object-fit: contain;
            }
          }
        }
      }
    }
  }
  
  .part-overrides-section {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      h3 {
        margin: 0;
      }
    }
    
    .part-overrides-list {
      margin-bottom: 20px;
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .expression-editor-container {
    padding: 10px;
    
    .content-layout {
      grid-template-columns: 1fr;
      
      .preview-section {
        margin-top: 20px;
      }
    }
  }
}
</style> 